package main

import (
	"fmt"
	"os"
	"strconv"
	"strings"
)

// define proxy with weight
type Proxy struct {
	addr           string
	weight         int
	currentWeight  int
}

func getProxiesObj(proxiesObj *[]*Proxy, proxiesArr []string) {
	for _, proxyWithWeight := range proxiesArr {
		pArr := strings.Split(proxyWithWeight, " ")
		if len(pArr) != 2 {
			fmt.Println("Some proxy items with weight is incorrect, please check if config is correct.")
			os.Exit(0)
		}
		w, err := strconv.Atoi(pArr[1])
		if err != nil {
			fmt.Printf("Can not parse proxy weight correctly: %s \n", err.Error())
			os.Exit(0)
		}
		*proxiesObj = append(*proxiesObj, &Proxy{pArr[0],w , 0})
	}
}

// refer from https://zoker.io/blog/write-http-lbproxy-with-wrr-and-go
func getBestProxy(proxies *[]*Proxy) (b *Proxy) {
	checkProxyLock.Lock()
	defer checkProxyLock.Unlock()
	allWeight := 0
	for _, proxy := range *proxies {
		if proxy == nil {
			return nil
		}
		allWeight += proxy.weight
		proxy.currentWeight += proxy.weight // x
		if b == nil || proxy.currentWeight > b.currentWeight {
			b = proxy
		}
	}

	if b == nil {
		fmt.Println("Can not find out a good proxy.")
		os.Exit(0)
	}
	b.currentWeight -= allWeight //x
	return b
}

